package igz.fleaxy.ui {
	import flash.display.Sprite;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import igz.fleaxy.Fleaxy;
	import igz.fleaxy.util.ObjectUtil;
	/**
	 * ...
	 * @author Intelygenz | www.intelygenz.com
	 */
	public class ParallaxManager {

		protected var _Layers:Array;
		protected var _OriginCoords:Array;
		protected var _Multipliers:Array;

		protected var _Settings:Object;

		protected var _DispX:Number;
		protected var _DispY:Number;
		public function get $DisplaceX() : Number {
			return _DispX;
		}
		public function get $DisplaceY() : Number {
			return _DispY;
		}
		public function set $DisplaceX(p_dispX:Number) : void {
			_DispX = p_dispX;
			$Calculate();
		}
		public function set $DisplaceY(p_dispY:Number) : void {
			_DispY = p_dispY;
			$Calculate();
		}

		public function ParallaxManager(p_settings:Object = null) {
			_Settings = { "infiniteScrolling" : false, "margins": "STAGE" };
			ObjectUtil.$Merge(p_settings, _Settings);
			_Layers = [];
			_OriginCoords = [];
			_Multipliers = [];
			_DispX = 0;
			_DispY = 0;
		}

		public function $AddLayer(p_layer:Sprite, p_multiplier:Number = -1) : void {
			_OriginCoords.push( new Point(p_layer.x, p_layer.y));
			_Multipliers.push( p_multiplier==-1 ? _Layers.length : p_multiplier );
			_Layers.push( p_layer );
		}

		public function $Calculate() : void {
			var layer:Sprite;
			var layerX:Number, layerY:Number;
			var f:uint, F:uint = _Layers.length;
			for (f = 0; f < F; f++ ) {
				layer = _Layers[f];
				layerX = (_OriginCoords[f] as Point).x+(_DispX * _Multipliers[f]);
				layerY = (_OriginCoords[f] as Point).y+(_DispY * _Multipliers[f]);
				if ( !_Settings["infiniteScrolling"] ) {
					if ( _Settings["margins"] == "STAGE" ) {
						if ( layerX < 0 ) {
							layerX = 0;
						}
						else if ( layerX + (layer.width * layer.scaleX) > Fleaxy.$Current.$Stage.stageWidth ) {
							layerX = Fleaxy.$Current.$Stage.stageWidth-(layer.width * layer.scaleX);
						}
						if ( layerY < 0 ) {
							layerY = 0;
						}
						else if ( layerY + (layer.height * layer.scaleY) > Fleaxy.$Current.$Stage.stageHeight ) {
							layerY = Fleaxy.$Current.$Stage.stageHeight-(layer.height * layer.scaleY);
						}
					}
				}

				layer.x = layerX;
				layer.y = layerY;

			}
		}

	}

}